package com.qms.repast.ui.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import butterknife.ButterKnife;

/**
 * @author 泅渡者
 * @date 2018/6/6 0006.
 * @describe: 基准Fragment
 */

public abstract class BaseFragment<P extends BasePresenter> extends Fragment {

	protected P mPresenter;
	protected BaseFragmentActivity mActivity;

	@Override
	public void onAttach (Context context) {
		super.onAttach(context);
		this.mActivity = (BaseFragmentActivity) context;
	}

	@Override
	public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(initLayout(), container, false);
		ButterKnife.bind(this, view);
		initPresenter();
		checkPresenterIsNull();
		initView(view, savedInstanceState);
		return view;
	}

	@Override
	public void onViewCreated (@NonNull View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		if (getUserVisibleHint()) {
			pullData();
		}
	}

	/**
	 * 加载布局
	 *
	 * @return
	 */
	protected abstract int initLayout ();

	/**
	 * 初始化Presenter
	 */
	protected abstract void initPresenter ();

	/**
	 * 预加载数据
	 */
	protected abstract void pullData ();

	@Override
	public void onDestroy () {
		super.onDestroy();
		mPresenter.detachView();
	}

	/**
	 * 初始化布局
	 *
	 * @param view
	 * @param savedInstanceState
	 */
	protected abstract void initView (View view, Bundle savedInstanceState);

	/**
	 * 获取宿主Activity
	 *
	 * @return
	 */
	public BaseFragmentActivity getHoldingActivity () {
		return mActivity;
	}

	private void checkPresenterIsNull () {
		if (mPresenter == null) {
			throw new IllegalStateException("please init mPresenter in initPresenter() method ");
		}
	}

}
